import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

const getCurrentDate = () => {
  const date = new Date()
 
  return {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    date: date.getDate()
  }
}

const initList = (year, month) => {
  const list = []

  // 1. 计算选中的年月的1号星期几
  const firstDate = new Date(year, month - 1, 1)
  let day = firstDate.getDay() // 0-6
  if (day === 0) {
    day = 7
  }

  // 2. 填充上个月
  // 2.1 计算上个月的最后一天
  const lastMonthLastDate = new Date(year, month - 1, 0)
  const an = lastMonthLastDate.getDate()
  // 2.2 上个月的总天数
  const n = day - 1
  const a0 = an - n + 1
  for (let i = a0; i <= an; i++) {
    list.push({ type: 'last', date: i })
  }

  // 3. 填充本月
  const monthLastDate = new Date(year, month, 0)
  // 3.1 本月的最后一天
  const bn = monthLastDate.getDate()
  for (let i = 1; i <= bn; i++) {
    list.push({ type: 'this', date: i })
  }

  // 4. 填充下个月
  const cn = 42 - n - bn
  for (let i = 1; i <= cn; i++) {
    list.push({ type: 'next', date: i })
  }

  return list
}
export const useYearsStore = defineStore('years', () => {
  
   const currentDate=getCurrentDate()
  const selecedDate=ref(currentDate)
  const year=computed({
    get:()=>selecedDate.value.year,
    set: (value) => {
      selecedDate.value.year = value
    }
  })
  const month=computed({
    get:()=>selecedDate.value.month,
    set: (value) => {
      selecedDate.value.month = value
    }
  })
  const date=computed({
    get:()=>selecedDate.value.date,
    set: (value) => {
      selecedDate.value.date = value
    }
  })

    const lists = computed(() => {
    return initList(year.value, month.value)
  })

 const formatDate = computed(() => {
    return `${year.value}-${month.value}-${date.value}`
  })
    const lastMonth = () => {
  // 计算本月的天数
  const thisMonthDays = new Date(year.value, month.value, 0).getDate()
  // 计算上个月的天数
  const prevMonthDays = new Date(year.value, month.value - 1, 0).getDate()

  if (prevMonthDays < thisMonthDays) {
    date.value = prevMonthDays
  }

  month.value = month.value - 1
  if (month.value < 1) {
    year.value = year.value - 1
    month.value = 12
  }
}
  // 操作下个月
  const nextMonth = () => {
  // 计算本月的天数
  const thisMonthDays = new Date(year.value, month.value, 0).getDate()
  // 计算上个月的天数
  const nextMonthDays = new Date(year.value, month.value + 1, 0).getDate()

  if (nextMonthDays < thisMonthDays) {
    date.value = nextMonthDays
  }
  month.value = month.value + 1
  if (month.value > 12) {
    year.value = year.value + 1
    month.value = 1
  }
}
  const backToToday = () => {
    selecedDate.value = getCurrentDate()
  }
  return { year, month, date , lastMonth, nextMonth, backToToday, lists, formatDate }
})
